/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.bigknow.appstore.server.rpc;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import com.bigknow.appstore.common.rpc.MuxAction;

public class SSLServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private ByteBuf buf;

    private SSLServer sslServer;

    private MuxActionHandler handler;

    private ChannelHandlerContext ctx;

    private static Timer timer = new Timer();

    private static Map<SSLServerHandler, Long> lastAccessTime = new ConcurrentHashMap<SSLServerHandler, Long>();

    static {
        timer.schedule(new TimerTask() {
            public void run() {
                for (Entry<SSLServerHandler, Long> entry : lastAccessTime.entrySet()) {
                    SSLServerHandler handler = entry.getKey();
                    if (System.currentTimeMillis() - entry.getValue() >= 20 * 1000 || !handler.ctx.channel().isOpen()) {
                        handler.exceptionCaught(handler.ctx, null);
                        lastAccessTime.remove(handler);
                    }
                }
            }
        }, 10 * 1000, 10 * 1000);
    }

    public SSLServerHandler(SSLServer sslServer) {
        this.sslServer = sslServer;
    }

    @Override
    public void channelActive(final ChannelHandlerContext ctx) {
        this.ctx = ctx;
        lastAccessTime.put(this, System.currentTimeMillis());
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        lastAccessTime.put(this, System.currentTimeMillis());
        if (buf == null) {
            buf = msg.copy();
        } else {
            buf = Unpooled.wrappedBuffer(buf, msg.copy());
        }
        if (handler == null) {
            if (buf.readableBytes() >= 4) {
                byte[] header = new byte[4];
                int readerIndex = buf.readerIndex();
                buf.readBytes(header);
                String code = new String(header);
                MuxAction action = MuxAction.fromCode(code);
                handler = sslServer.getHandler(action);
                handler.init(ctx);
                boolean clear = handler.handle(ctx, buf);
                if (clear) {
                    buf.release();
                    buf = null;
                }
            }
        } else {
            boolean clear = handler.handle(ctx, buf);
            if (clear) {
                buf.release();
                buf = null;
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) {
        try {
            channelInactive(ctx);
        } catch (Exception e) {
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        if (handler != null) {
            handler.notifyDisconnect(ctx);
        }
        ctx.close();
    }
}
